package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.nacos.common.utils.UuidUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ApArticleDto;
import com.heima.model.article.dtos.ApArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.common.dtos.ResponseResult;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.Date;
import java.util.HashMap;

/**
 * @Description TODO
 * @Author bo.li
 * @Date 2023/3/14 10:06
 * @Version 1.0
 */
@Slf4j
@Service
public class ApArticleServiceImpl implements ApArticleService {

    @Autowired
    private ApArticleMapper articleMapper;
    @Autowired
    private ApArticleConfigMapper configMapper;
    @Autowired
    private ApArticleContentMapper contentMapper;
    @Autowired
    private Configuration configuration;
    @Autowired
    private FileStorageService fileStorageService;

    /**  每页默认显示条数 */
    public final static int DEFAULT_SIZE = 10;
    /**  每页最大显示条数 */
    public final static int MAX_SIZE = 50;

    @Override
    public ResponseResult load(ApArticleHomeDto dto, Integer loadType) {
        //处理页数
        Integer size = dto.getSize();
        if(size == null || size <= 0){
            size = DEFAULT_SIZE;
        }
        size = Math.min(size, MAX_SIZE);

        dto.setSize(size);

        if(dto.getMaxBehotTime() == null){
            dto.setMaxBehotTime(new Date());
        }
        if(dto.getMinBehotTime() == null){
            dto.setMinBehotTime(new Date());
        }

        return ResponseResult.okResult(articleMapper.loadArticles(dto,loadType));
    }

    @Override
    public ResponseResult saveArticle(ApArticleDto articleDto) {
        log.info("文章添加到app端");
        ApArticle article = new ApArticle();
        BeanUtils.copyProperties(articleDto,article);
        article.setPublishTime(new Date());
        //todo:生成文章详情模拟板

        try {
            log.info("app添加数据，补充文章详情");
            String url = addMinio(articleDto.getContent());
            article.setStaticUrl(url);
        } catch (Exception e) {
            log.error("app添加数据,捕获异常", e);
        }

        if(article.getId() == null){
            articleMapper.insert(article);
            //保存config
            ApArticleConfig config = new ApArticleConfig(article.getId());
            configMapper.insert(config);

            //保存内容
            ApArticleContent content = new ApArticleContent();
            content.setContent(articleDto.getContent());
            content.setArticleId(article.getId());
            contentMapper.insert(content);
        }else{
            articleMapper.updateById(article);

            ApArticleContent articleContent = contentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, article.getId()));
            articleContent.setContent(articleDto.getContent());
            contentMapper.updateById(articleContent);
        }

        return ResponseResult.okResult(article.getId());
    }


    /**
     * 将文章添加到minIO中
     * @param content
     * @return
     * @throws Exception
     */

    private String addMinio(String content) throws Exception {
        //通过文章内容生成template模板
        Template template = configuration.getTemplate("article.ftl");

        HashMap<String, Object> map = new HashMap<>();
        map.put("content", JSONArray.parseArray(content));

        //接受模板生成数据
        StringWriter out = new StringWriter();
        template.process(map, out);
        //输出流输出数据到minio
        InputStream is = new ByteArrayInputStream(out.toString().getBytes());
        //4.修改ap_article表，保存static_url字段
        return fileStorageService.uploadHtmlFile("", UuidUtils.generateUuid() + ".html", is);


    }

    @Override
    public ApArticle getById(Long articleId) {
        return articleMapper.selectOne(new LambdaQueryWrapper<ApArticle>().eq(ApArticle::getAuthorId, articleId));
    }

    @Override
    public boolean commentActivation(Long articleId) {
        return configMapper.selectOne(new LambdaQueryWrapper<ApArticleConfig>().eq(ApArticleConfig::getArticleId, articleId)).getIsComment();
    }
}